<template>
  <n-card header-style="background-color:#fafafa" class="my-2 h-fit animate__animated animate__bounceInLeft"
    title="当前策略">
    <template #header-extra>
      <n-button type="primary" @click="goto('backtest')">
        策略不满意？调整一下
      </n-button>
    </template>
    <StrategyDescriptionComponent :data="strategy_description_data"/>
  </n-card>
  <n-card  header-style="background-color:#fafafa" class="my-2 h-fit animate__animated animate__bounceInLeft"
    title="策略报告">
    <n-flex justify="space-around" size="large">
      <ResultItemComponent v-for="i in base_list" :key="i.id" :data="i" />
    </n-flex>
  </n-card>
  <n-card header-style="background-color:#fafafa" class="my-2 h-fit animate__animated animate__bounceInLeft"
    title="结果分析">
    <ProcessAnalyzerComponent class="my-2" :date_list="report.date_list" :operation_list="report.operation_list"
      :return_list="report.return_list" :total_assets_list="report.total_assets_list" :daily_returns="report.daily_returns"
      :compare_stock="report.compare_stock" :item_list="report.item_list" :indicator_list="report.indicator_list" />
    <StrategyAnalyzerComponent :operation_return="report.operation_return" :operation_result="operation_result" />
    <div class="my-2">
      <StrategyAttributeComponent :data="report.attribute_list" :date_list="report.date_list"/>
    </div>
  </n-card>
</template>

<script setup>
import ResultItemComponent from '@/components/ResultItemComponent.vue';
import ProcessAnalyzerComponent from '@/components/backtest/ProcessAnalyzerComponent.vue';
import StrategyAnalyzerComponent from '@/components/backtest/StrategyAnalyzerComponent.vue';
import StrategyDescriptionComponent from '@/components/backtest/StrategyDescriptionComponent.vue';
import StrategyAttributeComponent from '@/components/backtest/StrategyAttributeComponent.vue';
import { useBacktestStore } from '@/stores/backtestStore';
const backtestStore = useBacktestStore();
import { useScenarioStore } from '@/stores/scenarioStore';
const scenarioStore = useScenarioStore();
import { ref, inject, onMounted } from 'vue';
import { useRouter } from 'vue-router';
const router = useRouter();

const report = inject('report');
const total_operation_list = ref([]);
const base_list = ref([]);
const strategy_description_data = ref({
  name:'',
  backtest_type:'',
  strategy_description:''
});
const operation_result = ref({
  max_stock_code: null,
  name: null,
  count: null,
  amount: null
});

// {
//     title: '预计年化收益率',
//     data: 15,
//     description: '收益较高',
//     color: 'red'
//   }


// data_list.push({
//   {
//     title: '预计年化收益率',
//     data: report.annual_returns,
//     description: '收益较高',
//     color: 'red'
//   }
// })
const getOperationList = () => {
  for (let i of report.value.operation_list) {
    for (let j of i) {
      total_operation_list.value.push(j);
    }
  }
}

const getBaseItem = (index_name, value) => {
  let base_item = {
    title: '',
    data: '',
    description: '',
    color: ''
  }
  if (index_name == 'annual_returns') {
    base_item.title = '预计年化收益率';
    base_item.data = (value * 100).toFixed(2);
    if (value >= 0 && value <= 0.03) {
      base_item.description = "收益较少";
      base_item.color = 'red';
    } else if (value > 0.03) {
      base_item.description = "收益较高";
      base_item.color = 'red';

    } else if (value >= -0.03 && value < 0) {
      base_item.description = "跌幅较少";
      base_item.color = 'green';

    } else if (value < -0.03) {
      base_item.description = "跌幅较高";
      base_item.color = 'green';
    }
  }
  if (index_name === "variance") {
    base_item.title = "风险";
    base_item.data = Math.max(value.toFixed(4), 0.0001);// 方差可能较小，可以保留到四位小数

    if (value >= 0 && value <= 0.01) {
      base_item.description = "风险较低";
      base_item.color = "green";
    } else if (value > 0.01 && value <= 0.02) {
      base_item.description = "风险适中";
      base_item.color = "yellow";
    } else if (value > 0.02) {
      base_item.description = "风险较高";
      base_item.color = "red";
    }
  }
  if (index_name === "complex") {
    base_item.title = "策略复杂度";
    base_item.data = value.toFixed(2); // 假设平均每天操作次数为小数，此处保留两位小数

    if (value >= 0 && value <= 2) {
      base_item.description = "复杂度较低";
      base_item.color = "green";
    } else if (value > 2 && value <= 5) {
      base_item.description = "复杂度适中";
      base_item.color = "yellow";
    } else if (value > 5) {
      base_item.description = "复杂度较高";
      base_item.color = "red";
    }
  }
  return base_item;
}
onMounted(() => {
  base_list.value.push(getBaseItem('annual_returns', report.value.annual_returns));
  base_list.value.push(getBaseItem('variance', report.value.variance));
  base_list.value.push(getBaseItem('complex', report.value.complex));
  getOperationList();
  let result = summarizeStockPurchases(total_operation_list.value);
  operation_result.value.max_stock_code = result.max_stock_code;
  operation_result.value.name = result.name;
  operation_result.value.amount = result.amount;
  operation_result.value.count = result.count;
  initStrategyDescriptionData();
})

const goto = function(url){
    router.replace({
        path:'/'+url
    });
}
async function initStrategyDescriptionData() {
 
  await scenarioStore.getScenarioById(backtestStore.form.baseinfo_form.scenario_id);
  strategy_description_data.value.name = scenarioStore.current_scenario.name;
  if(backtestStore.form.baseinfo_form.backtest_type=='stock'){
    strategy_description_data.value.backtest_type = '个股回测';
  }else{
    strategy_description_data.value.backtest_type = '组合回测';
  }
  for(let i of backtestStore.form.strategy_description_list){
    strategy_description_data.value.strategy_description += i.description+'；';
  }
}
function summarizeStockPurchases(purchases) {
  let summary = {};

  // 遍历采购记录
  for (let i = 0; i < purchases.length; i++) {
    // 如果交易类型是 BUY，则进行统计
    if (purchases[i].operation_type === "BUY") {
      // 判断是否是新的股票代码
      if (!summary[purchases[i].stock_code]) {
        summary[purchases[i].stock_code] = {
          count: 0,
          amount: 0,
          name: purchases[i].name
        };
      }
      // 累加购买次数和购买总量
      summary[purchases[i].stock_code].count += 1;
      summary[purchases[i].stock_code].amount += purchases[i].amount;
    }
  }
  // 找出买得最多的股票代码和购买总量
  let maxAmount = 0;
  let maxStockCode = '';
  for (let stockCode in summary) {
    if (summary[stockCode].amount > maxAmount) {
      maxAmount = summary[stockCode].amount;
      maxStockCode = stockCode;
    }
  }

  // 没有买入记录则返回空对象
  if (maxStockCode === '') {
    return {
      max_stock_code: null,
      name: null,
      count: null,
      amount: null
    }
  }

  // 返回统计结果
  let result = {
    max_stock_code: maxStockCode,
    name: summary[maxStockCode].name,
    count: summary[maxStockCode].count,
    amount: summary[maxStockCode].amount
  }
  return result;
}
</script>
